import './index.scss';

import { useState } from 'react';
import classNames from 'classnames';
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';

type CopyButtonProps = {
    copyText: string;
    type?: string;
    name?: string;
    className?: string;
    disabled?: boolean;
    onClick?: () => void; // 明确 onClick 的类型
};

function CopyBtn({ 
    copyText, 
    type = 'primary', 
    name = '复制', 
    className,
    disabled,
    onClick,
}: CopyButtonProps) {
    const [isCopied, setIsCopied] = useState(false); // 将状态提升到组件顶层
    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(copyText);
            setIsCopied(true); // 更新状态
            setTimeout(() => setIsCopied(false), 3000); // 3秒后重置状态
        } catch (err) {
            const textarea = document.createElement('textarea');
            textarea.value = copyText;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            setIsCopied(true); // 更新状态
            setTimeout(() => setIsCopied(false), 3000); // 3秒后重置状态
        }
        if (onClick) {
            onClick(); // 调用外部回调
        }
    };

    return (
        <button
            className={classNames('CopyButton', { 
                'CopyButtonGuest': type === 'guest',
                [className || '']: !!className
            })}
            onClick={handleCopy} // 直接绑定方法名
            type="button"
            disabled={disabled}
            aria-label="复制到剪贴板"
        >
            {isCopied ? <CheckOutlined /> : <CopyOutlined />}
            <span>{isCopied ? '已复制' : name}</span>
        </button>
    );
}

export default CopyBtn;